package dal

import (
	"database/sql"
	"fmt"
	"scheduler/config"

	_ "github.com/go-sql-driver/mysql"
	log "github.com/omidnikta/logrus"
)

var (
	db *sql.DB
)

func init() {
	log.StandardLogger().ShowCaller(true)

	openDB()
}

func openDB() {
	var (
		addr, user, passwd, dbname string
		pool                       int
	)

	err := config.Get("mysql:main:addr", &addr)
	if nil != err {
		log.Fatalln(err)
	}

	err = config.Get("mysql:main:user", &user)
	if nil != err {
		log.Fatalln(err)
	}

	err = config.Get("mysql:main:passwd", &passwd)
	if nil != err {
		log.Fatalln(err)
	}

	err = config.Get("mysql:main:dbname", &dbname)
	if nil != err {
		log.Fatalln(err)
	}

	err = config.Get("mysql:main:pool", &pool)
	if nil != err {
		log.Fatalln(err)
	}

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local", user, passwd, addr, dbname)
	log.Debugln("dsn:", dsn)
	db, err = sql.Open("mysql", dsn)
	if nil != err {
		log.Fatalln(err)
	}
	db.SetMaxIdleConns(pool)
	db.SetMaxOpenConns(pool)
}
